#!/usr/bin/python

import os
import sys
import shutil
import datetime
from optparse import OptionParser

# Setup

DIR_SVN_ROOT = r"/home/louis/cfg/jinglemansweep/devices/main_laptop/trunk"

# Initialisation

DIR_OS_ROOT = r""
datestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

# Argument Parsing

parser = OptionParser()
parser.add_option("-b", "--backup", dest="backup_filename", help="Backup file to repository", metavar="FILE")
parser.add_option("-r", "--restore", dest="restore_filename", help="Restore file from repository", metavar="FILE")
parser.add_option("-d", "--delete", dest="delete_filename", help="Delete file from repository", metavar="FILE")

(options, args) = parser.parse_args()

# Backup File

if options.backup_filename:
    if os.path.exists(options.backup_filename):
        src = "%s%s" % (DIR_OS_ROOT, options.backup_filename)
        dst = "%s%s" % (DIR_SVN_ROOT, options.backup_filename)
        print "Backing up '%s' to '%s'..." % (src, dst)
        bits = options.backup_filename.split("/")[1:]
        for i in range(0, len(bits)):
            path = ""
            for j in range(0, i):
                path = path + "/" + bits[j]
            repos_path = "%s/%s" %(DIR_SVN_ROOT, path)
            if not os.path.exists(repos_path):
                os.mkdir(repos_path)
        shutil.copy2(src, dst)

# Restore File

if options.restore_filename:
    if os.path.exists(options.restore_filename):
        src = "%s%s" % (DIR_SVN_ROOT, options.restore_filename)
        dst = "%s%s" % (DIR_OS_ROOT, options.restore_filename)
        print "Restoring '%s' to '%s'..." % (src, dst)
        shutil.copy2(dst, "%s.backup_%s" % (dst, datestamp))
        shutil.copy2(src, dst)

# Delete File

if options.delete_filename:
    if os.path.exists(options.delete_filename):
        print "Deleting '%s' from repository..." % (options.delete_filename)
        os.unlink("%s%s" % (DIR_SVN_ROOT, options.delete_filename))        